<template>
  <div class="list">
    <a-card>
      <div>
        <a-space class="operator">
          <a-button
            @click="addNew"
            type="primary"
          >新建</a-button>
        </a-space>
        <standard-table
          :columns="columns"
          :dataSource="data"
        >
          <div
            slot="description"
            slot-scope="{text}"
          >
            {{text}}
          </div>
          <div
            slot="operation"
            slot-scope="{record}"
          >
            <a
              @click='edit(record)'
              style="margin-right: 8px"
            >
              <a-icon type="edit" />编辑

            </a>
            <a
              @click="notice(record)"
              style="margin-right: 8px"
            >
              <a-icon type="delete" />删除
            </a>
          </div>
          <template slot="statusTitle">
            <a-icon
              @click.native="onStatusTitleClick"
              type="info-circle"
            />
          </template>
        </standard-table>
      </div>
    </a-card>
    <a-modal
      v-model="showModal"
      title="温馨提示"
      ok-text="确认"
      cancel-text="取消"
      @ok="deleteRecord"
    >
      是否删除"{{ currentRecord && currentRecord.name }}"分类
    </a-modal>

    <a-modal
      v-model="editing"
      title="编辑分类"
      ok-text="确认"
      cancel-text="取消"
      @ok="submit"
    >
      <a-form-model
        :model="form"
        ref="ruleForm"
      >
        <a-form-model-item
          label="分类名称"
          prop="name"
        >
          <a-input v-model="form.name" />
        </a-form-model-item>
        <a-form-model-item label="上级分类">
          <a-cascader
            placeholder="默认为顶级分类"
            :options="options"
            change-on-select
            :key="form.key"
            :defaultValue="[form.parent_id===0?0:form.parent_id]"
            @change="onSelect"
          />
        </a-form-model-item>
        <a-form-model-item label="排序(数字越小越靠前)">
          <a-input
            type="number"
            v-model="form.sort"
            placeholder="默认999"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>

</template>

<script>
import StandardTable from '@/pages/components/table/StandardTable'

export default {
  name: "list",
  props: ['columns', 'data', 'loading'],
  components: { StandardTable },
  beforeUpdate() {
    if (this.options.length === 1) {
      this.options = this.options.concat(this.data);
    }

  },
  mounted() {
    this.$emit('update') && this.$emit('update')
  },
  data() {
    return {
      form: {
        name: '',
        parent_id: '',
        sort: '',
        path: '',
        label: ''
      },
      advanced: true,
      selectedRows: [],
      showModal: false,
      currentRecord: '',
      editing: false,
      options: [
        {
          value: 0,
          label: '顶级分类'
        },
      ],
      valArr: [],
      valId: [],
      arr2: []
    }
  },

  methods: {
    //删除选中行
    deleteRecord() {
      let info = this.currentRecord;
      this.selectedRows = this.selectedRows.filter(item => item.key !== info.key)
      this.$emit('classifyDelete', info.key)
      sessionStorage.clear();
      this.showModal = false;
    },
    async submit() {
      if (!this.form.name) {
        this.$message.error('请输入分类名称');
        return;
      }
      this.editing = false;


      // 编辑更新
      if (this.currentRecord) {
        this.form.id = this.currentRecord.id;
        this.form.parent_id = this.form.parent_id.toString();
        await this.$emit('update', 1, this.form);
        this.options = [{
          value: 0,
          label: '顶级分类'
        },];
        //新增
      } else {
        await this.$emit('update', 2, this.form);
        this.options = [{
          value: 0,
          label: '顶级分类'
        },];
      }
      this.currentRecord = null;
    },
    notice(record) {
      this.currentRecord = record;
      this.showModal = true;
    },
    edit(record) {
      this.editing = true;
      this.valId = record.id;
      // 拷贝数据给修改表单使用
      this.form = JSON.parse(JSON.stringify(record));
      this.currentRecord = record;
      let path = (record.path.split(','));
      // 获取当前的分类id层次
      path = path.map(item => {
        return Number(item);
      })

      // 改变当前的层次，便于修改
      path.forEach((item, idx) => {
        this.$set(this.valArr, idx, item);
      })
      // 假如是最顶层分类，默认选择第一个
      // 自动默认是顶级分类
      if (this.valArr[0] == 0) {
        this.onSelect(this.valArr)
      }
    },
    onSelect(value) {
      this.valArr = value;
      // 预防选择的是本身作为父级，如选择自身，默认是顶级分类
      if (value.includes(this.valId) && (value[0] != 0)) {
        this.$message.error('不能选自身哦');
        this.$set(this.valArr, value.length - 1, value[value.length - 2]);
        return;
      }
      this.form.path = value.join();
      this.form.parent_id = value.slice(-1).join();
    },

    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    remove() {
      this.dataSource = this.dataSource.filter(item => this.selectedRows.findIndex(row => row.key === item.key) === -1)
      this.selectedRows = []
    },
    addNew() {
      this.editing = true;
      // 清空数据
      this.form = {};

      this.$set(this.valArr, 0, 0);
      this.valId = 0;
      this.currentRecord = null;
      this.onSelect([0]);
      this.$emit('update')
    },
    handleMenuClick(e) {
      if (e.key === 'delete') {
        this.remove()
      }
    },

    getMenu(arr) {
      arr.map(ele => {
        if (ele.children && ele.children.length > 0) {
          ele.children.map(ele => {
            this.arr2.push(ele)
          })
          this.getMenu(ele.children)
        } else {
          this.arr2.push(ele)
        }
      })
    },

  },



}
</script>

<style lang="scss" scoped>
.list {
  padding: 5px;
  background-color: #fff;
}
.ant-table-wrapper {
  margin-top: 5px;
}
.ant-btn {
  margin-right: 10px;
}
.card-avatar {
  width: 48px;
  height: 48px;
  border-radius: 48px;
}

.meta-content {
  position: relative;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  height: 64px;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}
</style>